package com.neuedu.security.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.neuedu.security.entity.SysUser;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JWTUtils {


    /**
     * 生成token
     * @param user
     * @return
     * @throws Exception
     */
    public static String generator(SysUser user) throws Exception {
        JWTCreator.Builder builder = JWT.create();
        String token = builder
                    .withClaim("user_id",user.getUserId())
                    .withClaim("username",user.getUserName())
                .withClaim("password",user.getPassword())

//                .withClaim("lastlogin",new Date())
                .sign(Algorithm.HMAC256("123456789"));

//        System.out.println("token = " + token);

        return token;
    }


    /**
     * 解析token
     * @param token
     * @return
     * @throws Exception
     */
    public static SysUser decode(String token) throws Exception {
        JWTVerifier build = JWT.require(Algorithm.HMAC256("123456789")).build();

        SysUser user = null;
//        String token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.8kDrRL2ziI2is6k4feGUoSFk7NzodsY5F1sEIqk4zzY";
        try{
            DecodedJWT verify = build.verify(token);
            user = new SysUser();
            user.setUserId(verify.getClaim("user_id").asLong());
            user.setUserName(verify.getClaim("username").asString());
            user.setPassword(verify.getClaim("password").asString());
//            user.setLoginDate(verify.getClaim("lastlogin").asDate());
        }catch (Exception e){
            log.warn("token {}  解析失败了",token);
        }

        return user;

    }


}
